<?php
class Router {

    var $routes = array();
    var $subdir;
    var $class;
    var $method;
    var $arguments;
    var $segments;

    function Router() {
    }

    // stolen from codeigniter
    function parse_controller($uri) {

        if (ends_with($uri,'/')) $uri = substr($uri,0,-1); // gets rid of trailing slash

        $this->segments = explode('/', $uri);

        // check to see if a subdirectory in controllers
        // just one level deep currently
        if (is_dir(WEB_ROOT . '/app/controllers/' . $this->segments[0])) {
            $this->subdir = $this->segments[0];
            if (count($this->segments) > 1) {
                $this->segments = array_slice($this->segments, 1);
            } else {
                // just overwrite this so the code below can work as previous
                $this->segments[0] = "";
            }
        }

        $controller = ucfirst($this->segments[0]. 'Controller');

        if ($this->subdir == "") {
            $classFile = WEB_ROOT . '/app/controllers/' . $controller . EXT;
        } else {
            $classFile = WEB_ROOT . '/app/controllers/' . $this->subdir . '/' . $controller . EXT;
        }

        // check to see if in default
        if ($this->segments[0] != ""  && file_exists($classFile)) {
            $this->class = $this->segments[0];
            $this->segments = array_slice($this->segments, 1);
        } else {
            $this->class = "default";
            $this->method = "index";
            return;
        }

        // since greater than 1
        if (count($this->segments) > 0) {
            $this->method = $this->segments[0];
            // now remaining are arguments
            $this->segments = array_slice($this->segments, 1);
        } else {
            // will never be arguments
            $this->method = "index";
            $this->segments = array();
        }
        return;

        // nothing hit, default or subdirectory
        redirect("/error/404.php?nothing_found2");
    }

}